﻿using System;
using System.Diagnostics;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

using Purchasing.Application.Enums;

/// <summary>
/// 错误处理Filter
/// </summary>
namespace Web.Filters
{
    public class MyExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<MyExceptionFilter> _logger;

        public MyExceptionFilter(ILogger<MyExceptionFilter> logger)
        {
            this._logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
           
            if (!Utility.StaticVariables.Aspnetcore_Environment.Equals(nameof(EnvironmentEnums.Development)))
            {
                if (!context.ExceptionHandled) //处理未处理的错误
                {
                    context.ExceptionHandled = true;
                    // 解析异常信息
                    var (StatusCode, ErrorCode, Errors) = UnifyContext.GetExceptionMetadata(context);
                    //写入错误日志
                    _logger.LogError(context.Exception, Errors.ToString(), Errors);
                    if (StatusCode == 404)
                    {
                        context.HttpContext.Response.Redirect("../Error/error-404.html");
                    }
                    else if (StatusCode == 403 || StatusCode == 401)
                    {
                        context.HttpContext.Response.Redirect("../Error/error-403.html");
                    }
                    else if (StatusCode == 500)
                    {
                        context.HttpContext.Response.Redirect("../Error/error-500.html");
                    }
                    else
                    {

                    }
                }
            }
            
         }
    }
}
